<template>
  <div class="kva-container">
    <div class="kva-contentbox">
      <home-page-header>
        <div class="kva-form-search">
          <el-form class="search-form" :inline="true" :model="queryParams" ref="searchForm">
            <el-form-item>
              <el-button type="primary" icon="Plus" @click="handleCreateBatchCode">创建钱包兑换码</el-button>
            </el-form-item>
            <el-form-item  v-if="selectIds.length > 0">
              <el-button type="danger" icon="Delete" @click="handleBatchDels">批量回收站</el-button>
            </el-form-item>
            <el-form-item label="充值金额" prop="vipId">
              <el-input placeholder="请输入充值的面值金额" v-model="queryParams.coin"></el-input>
            </el-form-item>
            <el-form-item label="兑换码：" prop="code">
              <el-input v-model="queryParams.code" placeholder="请输入兑换码..." maxlength="100" clearable />
            </el-form-item>
            <el-form-item label="使用状态" prop="mark">
              <el-select v-model="queryParams.mark" class="m-2" placeholder="请选择" clearable  @change="handleSearch">
                <el-option
                    v-for="item in [
                    { value: 1, label: '已使用' },
                    { value: 0, label: '未使用' }
                  ]"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click.prevent="handleSearch">搜索</el-button>
              <el-button type="danger" icon="Refresh" @click.prevent="handleReset">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
        <div v-if="selectIds.length>0" class="mb10">
          <el-alert
              size="small"
              @close="handleAlertClose"
              :title="'选中了（' + selectIds.length + '）项数据'"
              type="success"
              show-icon
          />
        </div>
        <el-table
            v-loading="tableLoading"
            ref="tableRef"
            row-key="id"
            :data="tableData"
            stripe
            border
            :row-class-name="tableRowClassName"
            @selection-change="handleSelectionChange"
            :height="tableHeight"
        >
          <el-table-column fixed type="selection" width="55"/>
          <el-table-column fixed label="序号" width="100" align="center">
            <template v-slot="scope">
              <span>{{ scope.$index + 1 }}</span>
            </template>
          </el-table-column>
          <el-table-column label="充值金额" align="center" prop="coin"></el-table-column>
          <el-table-column label="兑换码" prop="code" align="center" />
          <el-table-column label="使用状态"  width="180" align="center">
            <template #default="scope">
              <el-switch
                  v-model="scope.row.mark"
                  @change="handleStatus(scope.row, 'mark')"
                  :active-value="1"
                  active-color="#4caf50"
                  active-text="已使用"
                  inactive-text="未使用"
                  :inactive-value="0"
                  :height="settings.tableHeight()"
              >
              </el-switch>
            </template>
          </el-table-column>
          <el-table-column label="创建时间" width="200" align="center">
            <template #default="scope">
              <span>{{ formatTimeToStr(scope.row.createTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="更新时间" width="200" align="center">
            <template #default="scope">
              <span>{{ formatTimeToStr(scope.row.updateTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="操作" align="right" width="280">
            <template #default="scope">
              <el-button icon="edit" type="primary" size="small" @click.stop="handleEdit(scope.row)">编辑</el-button>
              <el-button icon="remove" type="danger" size="small" @click.stop="handleDel(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="kva-pagination-box center">
          <el-pagination
              :current-page="queryParams.pageNo"
              :page-size="queryParams.pageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
          />
        </div>
      </home-page-header>
    </div>
  </div>
</template>
<script setup>
import settings from '@/settings'
import KVA from '@/utils/kva.js'
import { formatTimeToStr } from '@/utils/date.js'
import { findPages, removeById, updateStatus,createBatchCode,batchRemoves } from '@/api/users/walletcode.js'

// 搜索属性定义
const queryParams = reactive({
  pageNo: 1,
  pageSize: 30,
  coin: '',
  mark: '',
  code: ''
})

// 定义响应式得列表数据容器
const tableRef = ref({})
const tableData = ref([])
const tableLoading = ref(false)
const searchForm = ref({})
const total = ref(0)
const pages = ref(0)
const selectIds = ref([])
const showAlert = ref(false)
const tableHeight = ref('calc(100vh - 265px)')
// 加载数据
const handleLodeData = async () => {
  tableLoading.value = true
  const resp = await findPages(queryParams)
  tableData.value = resp.data.records
  total.value = resp.data.total * 1
  pages.value = resp.data.pages * 1
  tableLoading.value = false
}


// 改变行颜色
const tableRowClassName = ({ row, rowIndex }) => {
  if (row.loadmore == 1) {
    return 'hot-row'
  }
  return ''
}



// 清空选择
const handleAlertClose = () => {
  showAlert.value = false
  tableRef.value.clearSelection()
}


/**
 * 选择删除的元素
 * @param rows
 */
const handleSelectionChange = (rows) => {
  showAlert.value = rows.length > 0
  selectIds.value = rows.map((c) => c.id)
  tableHeight.value = rows.length > 0 ? 'calc(100vh - 310px)' : 'calc(100vh - 265px)'
}


// 搜索
const handleSearch = () => {
  queryParams.pageNo = 1
  handleLodeData()
}

// 重置
const handleReset = () => {
  searchForm.value.resetFields()
  handleSearch()
}

// 分页size更改
const handleSizeChange = (size) => {
  queryParams.pageSize = size
  handleLodeData()
}

// 分页pageNo更改
const handleCurrentChange = (pno) => {
  queryParams.pageNo = pno
  handleLodeData()
}

// 添加事件
const handleCreateBatchCode = () => {
  if(!queryParams.coin){
    KVA.error("请填写充值金额！")
    return
  }
  createBatchCode({coin:queryParams.coin})
  KVA.success(`以为你创建1个面值是：【${queryParams.coin}】的兑换码!!"`)
  queryParams.coin = ""
  handleLodeData()
}

// 删除
const handleDel = (row) => {
  KVA.confirm('警告', '<strong>您确定要执行此次操作吗？</strong>', { icon: 'success' }).then(async () => {
    await removeById(row.id)
    KVA.notifySuccess('删除成功!')
    handleLodeData()
  })
}


/**
 * 批量加入回收站
 */
const handleBatchDels = () => {
  if (selectIds.value && selectIds.value.length == 0) {
    KVA.notifyError('请选择一个项进行操作！')
    return
  }

  KVA.confirm('警告', '<strong>您确定要执行此次【批量删除】操作吗？</strong>', { icon: 'success' }).then(
      async () => {
        const ids = selectIds.value.join(',')
        await batchRemoves(ids)
        KVA.notifySuccess('批量恢复成功!')
        handleLodeData()
      }
  )
}

// 更新状态
const handleStatus = async (row, field) => {
  await updateStatus(row.id, field, row[field])
  handleLodeData()
  KVA.notifySuccess('操作成功!')
}

onMounted(() => {
  handleLodeData()
})
</script>
